import 'package:citiesocial/_include.dart';
import 'package:citiesocial/widgets/f4system/my_drop_down_button.dart';

class MyAddressAdd extends BaseStatefulWidget {
  final String _addressId;
  MyAddressAdd([this._addressId]);

  @override
  State<StatefulWidget> createState() => _MyAddressAddState();
}

class _MyAddressAddState extends BaseState<MyAddressAdd> {
  _MyAddressAddState();
  static const _itemHeight = 55.0;

  final _firstNameController = TextEditingController();
  final _lastNameController = TextEditingController();
  // final _countryController = TextEditingController();
  // final _deliverController = TextEditingController();
  // final _areaController = TextEditingController();
  final _streetController = TextEditingController();
  final _phoneController = TextEditingController();

  final _countries = List<CountryEntity>();
  final _provinces = List<AreaEntity>();
  final _cities = List<CityEntity>();
  CountryEntity _selectedCountry;
  AreaEntity _selectedProvince;
  CityEntity _selectedCity;

  void _onMenuTap() {
    final firstName = _firstNameController.text;
    if (firstName == null || firstName.length == 0) {
      Toast.show(context, '姓不能为空');
      return;
    }
    final lastName = _lastNameController.text;
    if (lastName == null || lastName.length == 0) {
      Toast.show(context, '名不能为空');
      return;
    }
    if (_selectedCountry == null && _countries.length > 0) {
      Toast.show(context, '国家不能为空');
      return;
    }
    final country = _selectedCountry?.country ?? ' ';
    if (_selectedProvince == null && _provinces.length > 0) {
      Toast.show(context, '行政区不能为空');
      return;
    }
    final province = _selectedProvince?.province ?? ' ';
    if (_selectedCity == null && _cities.length > 0) {
      Toast.show(context, '城市不能为空');
      return;
    }
    final city = _selectedCity?.city ?? ' ';
    final street = _streetController.text;
    if (street == null || street.length == 0) {
      Toast.show(context, '街道不能为空');
      return;
    }
    final phone = _phoneController.text;
    if (phone == null || phone.length == 0) {
      Toast.show(context, '手机号不能为空');
      return;
    }
    LoadingDialog.show(context);
    if (widget._addressId == null) {
      HttpManager.addAddress(Configs.userId, Configs.userToken, lastName,
              firstName, country, province, city, street, phone,
              context: context)
          .then((yes) async {
        await LoadingDialog.dismiss(context);
        if (yes) {
          await Toast.show(context, '添加成功');
          Navigator.maybePop(context);
        }
      });
    } else {
      HttpManager.updateAddress(
              Configs.userId, Configs.userToken, widget._addressId,
              surname: lastName,
              name: firstName,
              country: country,
              province: province,
              city: city,
              address: street,
              mobile: phone,
              context: context)
          .then((yes) async {
        await LoadingDialog.dismiss(context);
        if (yes) {
          await Toast.show(context, '修改成功');
          Navigator.maybePop(context);
        }
      });
    }
  }

  void _loadDetailIfCan() {
    if (widget._addressId != null) {
      HttpManager.addressDetail(
              Configs.userId, Configs.userToken, widget._addressId,
              context: context)
          .then((address) {
        if (address != null) {
          _firstNameController.text = address.name;
          _lastNameController.text = address.surname;
          _streetController.text = address.address;
          _phoneController.text = address.mobile;
          setState(() {});
        }
      });
    }
  }

  void _loadCountry() {
    LoadingDialog.show(context);
    HttpManager.country().then((countries) {
      LoadingDialog.dismiss(context);
      _countries.clear();
      _countries.addAll(countries);
      setState(() {});
    });
  }

  void _loadProvinceByCountry(CountryEntity country) {
    if (country == null) return;
    LoadingDialog.show(context);
    HttpManager.area(country.id).then((provinces) {
      LoadingDialog.dismiss(context);
      _provinces.clear();
      _provinces.addAll(provinces);
      setState(() {});
    });
  }

  void _loadCityByProvince(AreaEntity province) {
    if (province == null) return;
    LoadingDialog.show(context);
    HttpManager.city(province.id).then((cities) {
      LoadingDialog.dismiss(context);
      _cities.clear();
      _cities.addAll(cities);
      setState(() {});
    });
  }

  @override
  void initState() {
    Future.delayed(Configs.loadDelay, () {
      _loadCountry();
      _loadDetailIfCan();
    });
    super.initState();
  }

  @override
  void dispose() {
    _firstNameController.dispose();
    _lastNameController.dispose();
    // _countryController.dispose();
    // _deliverController.dispose();
    // _areaController.dispose();
    _streetController.dispose();
    _phoneController.dispose();

    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBarUtils.normal(
        context,
        widget._addressId == null ? '新增收件地址' : '修改收件地址',
        GestureDetector(
          onTap: _onMenuTap,
          child: Container(
            padding: AppBarUtils.inner_image_padding,
            child: Center(
              child: Text(
                '完成',
                style: TextStyle(
                    color: Colors.grey, fontSize: AppBarUtils.menu_font_size),
              ),
            ),
          ),
        ),
      ),
      backgroundColor: Colors.white,
      body: SafeArea(
        child: ListView(
          children: <Widget>[
            Container(
              padding: EdgeInsets.symmetric(horizontal: 15.0),
              child: Align(
                child: Text(getString('receiver')),
                alignment: Alignment.centerLeft,
              ),
              height: _itemHeight,
            ),
            Container(
              padding: EdgeInsets.symmetric(horizontal: 15.0),
              child: Row(
                children: <Widget>[
                  Container(
                    child: Text(
                      getString('first_name'),
                      style: TextStyle(fontSize: 16.0),
                    ),
                    margin: EdgeInsets.only(right: 20.0),
                  ),
                  Expanded(
                    child: TextFormField(
                      controller: _firstNameController,
                      decoration: InputDecoration(border: InputBorder.none),
                      style: TextStyle(
                        fontSize: 16.0,
                        color: Colors.black,
                      ),
                      maxLines: 1,
                    ),
                  ),
                ],
              ),
              height: _itemHeight,
              color: Colors.white,
            ),
            Configs.dividerLine,
            Container(
              padding: EdgeInsets.symmetric(horizontal: 15.0),
              child: Row(
                children: <Widget>[
                  Container(
                    child: Text(
                      getString('last_name'),
                      style: TextStyle(fontSize: 16.0),
                    ),
                    margin: EdgeInsets.only(right: 20.0),
                  ),
                  Expanded(
                    child: TextFormField(
                      controller: _lastNameController,
                      decoration: InputDecoration(border: InputBorder.none),
                      style: TextStyle(
                        fontSize: 16.0,
                        color: Colors.black,
                      ),
                      maxLines: 1,
                    ),
                  ),
                ],
              ),
              height: _itemHeight,
              color: Colors.white,
            ),
            Configs.dividerLine,
            Container(
              padding: EdgeInsets.symmetric(horizontal: 15.0),
              child: Align(
                child: Text(getString('contact_info')),
                alignment: Alignment.centerLeft,
              ),
              height: _itemHeight,
            ),
            Container(
              padding: EdgeInsets.symmetric(horizontal: 15.0),
              child: Row(
                children: <Widget>[
                  Container(
                    child: Text(
                      getString('country'),
                      style: TextStyle(fontSize: 16.0),
                    ),
                    margin: EdgeInsets.only(right: 20.0),
                  ),
                  FixedDropdownButton<CountryEntity>(
                    value: _selectedCountry,
                    style: TextStyle(
                      fontSize: 16.0,
                      color: Colors.black,
                    ),
                    items: _countries.map((country) {
                      return FixedDropdownMenuItem<CountryEntity>(
                        value: country,
                        child: SizedBox(
                          width: 200.0,
                          child: Text(
                            '${country.country}',
                            maxLines: 1,
                            overflow: TextOverflow.ellipsis,
                          ),
                        ),
                      );
                    }).toList(),
                    onChanged: (item) {
                      _loadProvinceByCountry(item);
                      _selectedProvince = null;
                      _selectedCity = null;
                      setState(() {
                        _selectedCountry = item;
                      });
                      print(item);
                    },
                  ),
                ],
              ),
              height: _itemHeight,
              color: Colors.white,
            ),
            Configs.dividerLine,
            Container(
              padding: EdgeInsets.symmetric(horizontal: 15.0),
              child: Row(
                children: <Widget>[
                  Container(
                    child: Text(
                      '行政区',
                      style: TextStyle(fontSize: 16.0),
                    ),
                    margin: EdgeInsets.only(right: 20.0),
                  ),
                  FixedDropdownButton<AreaEntity>(
                    value: _selectedProvince,
                    style: TextStyle(
                      fontSize: 16.0,
                      color: Colors.black,
                    ),
                    items: _provinces.map((province) {
                      return FixedDropdownMenuItem<AreaEntity>(
                        value: province,
                        child: ConstrainedBox(
                          constraints:
                              BoxConstraints.loose(Size.fromWidth(200.0)),
                          child: Text(
                            '${province.province}',
                            maxLines: 1,
                            overflow: TextOverflow.ellipsis,
                          ),
                        ),
                      );
                    }).toList(),
                    onChanged: (item) {
                      _loadCityByProvince(item);
                      _selectedCity = null;
                      setState(() {
                        _selectedProvince = item;
                      });
                      print(item);
                    },
                  ),
                ],
              ),
              height: _itemHeight,
              color: Colors.white,
            ),
            Configs.dividerLine,
            Container(
              padding: EdgeInsets.symmetric(horizontal: 15.0),
              child: Row(
                children: <Widget>[
                  Container(
                    child: Text(
                      '城市',
                      style: TextStyle(fontSize: 16.0),
                    ),
                    margin: EdgeInsets.only(right: 20.0),
                  ),
                  FixedDropdownButton<CityEntity>(
                    value: _selectedCity,
                    style: TextStyle(
                      fontSize: 16.0,
                      color: Colors.black,
                    ),
                    items: _cities.map((city) {
                      return FixedDropdownMenuItem<CityEntity>(
                        value: city,
                        child: ConstrainedBox(
                          constraints:
                              BoxConstraints.loose(Size.fromWidth(200.0)),
                          child: Text(
                            '${city.city}',
                            maxLines: 1,
                            overflow: TextOverflow.ellipsis,
                          ),
                        ),
                      );
                    }).toList(),
                    onChanged: (item) {
                      setState(() {
                        _selectedCity = item;
                      });
                      print(item);
                    },
                  ),
                ],
              ),
              height: _itemHeight,
              color: Colors.white,
            ),
            Configs.dividerLine,
            Container(
              padding: EdgeInsets.symmetric(horizontal: 15.0),
              child: Row(
                children: <Widget>[
                  Container(
                    child: Text(
                      '街道地址',
                      style: TextStyle(fontSize: 16.0),
                    ),
                    margin: EdgeInsets.only(right: 20.0),
                  ),
                  Expanded(
                    child: TextFormField(
                      controller: _streetController,
                      decoration: InputDecoration(border: InputBorder.none),
                      style: TextStyle(
                        fontSize: 16.0,
                        color: Colors.black,
                      ),
                      maxLines: 1,
                    ),
                  ),
                ],
              ),
              height: _itemHeight,
              color: Colors.white,
            ),
            Configs.dividerLine,
            Container(
              padding: EdgeInsets.symmetric(horizontal: 15.0),
              child: Row(
                children: <Widget>[
                  Container(
                    child: Text(
                      '手机号',
                      style: TextStyle(fontSize: 16.0),
                    ),
                    margin: EdgeInsets.only(right: 20.0),
                  ),
                  Expanded(
                    child: TextFormField(
                      controller: _phoneController,
                      decoration: InputDecoration(border: InputBorder.none),
                      style: TextStyle(
                        fontSize: 16.0,
                        color: Colors.black,
                      ),
                      maxLines: 1,
                    ),
                  ),
                ],
              ),
              height: _itemHeight,
              color: Colors.white,
            ),
            Configs.dividerLine,
          ],
        ),
      ),
    );
  }
}
